from motor.motor_asyncio import AsyncIOMotorClient
from config.settings import settings

client: AsyncIOMotorClient = None

async def connect_to_mongo():
    """连接到 MongoDB 数据库"""
    global client
    try:
        client = AsyncIOMotorClient(
            settings.MONGODB_URL,
            serverSelectionTimeoutMS=5000
        )
        # 测试连接和认证
        db = client[settings.MONGODB_DB_NAME]
        await db.command('ping')
        print(f"✅ MongoDB 连接成功: {settings.MONGODB_DB_NAME}")
    except Exception as e:
        print(f"❌ MongoDB 连接失败: {e}")
        raise

async def close_mongo_connection():
    """关闭 MongoDB 连接"""
    global client
    if client:
        client.close()
        print("✅ MongoDB 连接已关闭")

def get_database():
    """获取数据库实例"""
    if client is None:
        raise Exception("数据库未连接，请先调用 connect_to_mongo()")
    return client[settings.MONGODB_DB_NAME]

